package com.redwine.app.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.redwine.app.APP;
import com.redwine.app.MessageAddressBookActivity;
import com.redwine.app.R;
import com.redwine.app.chat.ChatActivity;
import com.redwine.app.chat.ChatConstant;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.MessageListResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.AlertDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 通讯里的适配器
 * 作者：gassion on 17/8/30 00:49
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MessageAddressBookAdapter extends BaseAdapter implements SectionIndexer {
    private ArrayList<MessageListResponse.DataEntity> dataEntityArrayList;
    private Context mContext;

    public MessageAddressBookAdapter(Context mContext, ArrayList<MessageListResponse.DataEntity> dataEntityArrayList) {
        this.mContext = mContext;
        this.dataEntityArrayList = dataEntityArrayList;
    }

    public List<MessageListResponse.DataEntity> getData() {
        if (null != dataEntityArrayList && !dataEntityArrayList.isEmpty()) {
            return dataEntityArrayList;
        } else {
            return new ArrayList<>();
        }
    }

    public void updateListView(ArrayList<MessageListResponse.DataEntity> dataEntityArrayList) {
        this.dataEntityArrayList = dataEntityArrayList;
        notifyDataSetChanged();
    }

    public int getCount() {
        return this.dataEntityArrayList.size();
    }

    public Object getItem(int position) {
        return dataEntityArrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup arg2) {
        ViewHolder viewHolder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.activity_message_address_book_item, null);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        final MessageListResponse.DataEntity dataEntity = dataEntityArrayList.get(position);
        int section = getSectionForPosition(position);
        if (position == getPositionForSection(section)) {
            viewHolder.addressbooktvletter.setVisibility(View.VISIBLE);
            viewHolder.addressbooktvletter.setText(dataEntity.getSortLetters());
        } else {
            viewHolder.addressbooktvletter.setVisibility(View.GONE);
        }
        viewHolder.addressbooktvusername.setText(dataEntity.getNickname());
        viewHolder.addressbooktvcontent.setText("");
        BitmapUtils.loadImage(viewHolder.addressbookivusericon, dataEntity.getAvatar(), BitmapUtils.ROUND);
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(mContext.getString(R.string.hint));
                builder.setMessage(mContext.getString(R.string.sure_to_delete_the_contact));
                builder.setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestDelContact(dataEntity.getFriend_uid(), position);
                    }
                });
                AlertDialog mDialog = builder.create();
                mDialog.setCancelable(false);
                mDialog.show();
                return false;
            }
        });
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ChatActivity.class);
                intent.putExtra(ChatConstant.EXTRA_USER_NICK_NAME, dataEntity.getNickname());
                intent.putExtra(ChatConstant.EXTRA_USER_ID, dataEntity.getUid());
                intent.putExtra(ChatConstant.EXTRA_USER_AVATAR, dataEntity.getAvatar());
                mContext.startActivity(intent);
            }
        });
        return view;

    }


    public int getSectionForPosition(int position) {
        return dataEntityArrayList.get(position).getSortLetters().charAt(0);
    }

    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = dataEntityArrayList.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    public class ViewHolder {
        public final TextView addressbooktvletter;
        public final ImageView addressbookivusericon;
        public final TextView addressbooktvusername;
        public final TextView addressbooktvcontent;
        public final View root;

        public ViewHolder(View root) {
            addressbooktvletter = (TextView) root.findViewById(R.id.address_book_tv_letter);
            addressbookivusericon = (ImageView) root.findViewById(R.id.address_book_iv_user_icon);
            addressbooktvusername = (TextView) root.findViewById(R.id.address_book_tv_user_name);
            addressbooktvcontent = (TextView) root.findViewById(R.id.address_book_tv_content);
            this.root = root;
        }
    }

    private void requestDelContact(final String friend_uid, final int position) {
        String url = NetworkConstants.FRIEND_DEL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("friend_uid", friend_uid);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                Utils.showToast(response.getMsg());
                if (response.isSuccess()) {
                    dataEntityArrayList.remove(position);
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(friend_uid, EaseCommonUtils.getConversationType(EaseConstant.CHATTYPE_SINGLE), true);
                    if (null != conversation)
                        conversation.clearAllMessages();
                    ((MessageAddressBookActivity) mContext).refreshData();
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MESSAGE_DATA));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }
}